package com.minshenglife.zanzan.web.weixin.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.minshenglife.zanzan.pub.message.WXRespMessage;
import com.minshenglife.zanzan.pub.message.custservice.GetAccessTokenMessage;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.web.service.RequestTaskService;
import com.nationsky.pub.utils.GsonUtils;
import com.nationsky.pub.utils.StringUtils;

import net.sf.json.JSONObject;

public class EMOWXBaseServcie {
	static Logger log = LoggerFactory.getLogger(EMOWXBaseServcie.class);
	 /**
     * 移动用户分组接口
     */
    public static String REMOVE_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=ACCESS_TOKEN";
    
    /**
     * 移动用户分组 0为正常
     * @param token 开发者凭据
     * @param jsonStr
     */
    public static boolean removeUserGroup(String jsonStr,String token){
    	log.debug("start removeUserGroup(String jsonStr) method");
    	log.debug("post json is ("+jsonStr+")");
    	try {
            //拼装移动用户分组的URL
        	String url = getremoveUserGroupUrl().replace("ACCESS_TOKEN", token);
        	//调用接口移动用户分组名
        	String json=RequestTaskService.sendDataStream(url, jsonStr);
        	log.debug("weixin grouping result " + json);
        	JSONObject jsonObject = JSONObject.fromObject(json);
        	if(null !=jsonObject){
        		if (0 != jsonObject.getInt("errcode")) {  
                   return false;
                }else{
                	return true;
                }
        	}
		} catch (Exception e) {
			return false;
		}
		return false;   	
    }
    
  /**
  * 创建用户分组接口
  */
 public static String CREATE_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN";
 
 /**
  * 创建分组
  * @param appId 开发者凭据
  * @param appSecret
  */
 public static boolean creatUserGroup(String jsonStr,String token){
 	try {
         //拼装创建分组的url
     	String url = CREATE_USER_GROUP.replace("ACCESS_TOKEN", token);
     	//调用接口创建分组
     	String json = RequestTaskService.sendDataStream(url, jsonStr);
    	log.debug("weixin grouping result " + json);
    	JSONObject jsonObject = JSONObject.fromObject(json);
     	if(null !=jsonObject){
     		if (jsonObject.containsKey("errcode")) {  
                 return false;
             }else{
             	return true;
             }
     	}
		} catch (Exception e) {
			return false;
		}
 	
 	return false;
 }
    /**
	 * 获取微信访问token
	 * @return
	 * @throws Exception
	 */
	public static String getWXAccessToken() throws Exception{
		String json=RequestTaskService.sendDataStream(getAccessTokenUrl(), null);
		log.debug("getWXAccessToken() :" +json);
		WXRespMessage resp=GsonUtils.fromGson(json, WXRespMessage.class);
		//请求出错
		if(resp.getErrcode()!=null && !"0".equals(resp.getErrcode())){
			log.debug("请求Access_Token时，出现异常：" +json);
			return null;
		}else{
			return resp.getAccess_token();
		}
		 
	}
    /**
	 * 获取AccessToken Url
	 * @return
	 */
	private  static String getAccessTokenUrl(){
		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WXKeys.WX_EMO_APPID+"&secret="+WXKeys.WX_EMO_SECRET;
		return url;
	}
	/**
	 * 获取移动用户分组接口url
	 * @return
	 */
	private  static String getremoveUserGroupUrl(){
		String url="https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=ACCESS_TOKEN";
		return url;
	}
	public static GetAccessTokenMessage getAccessTokenByCode(String code) throws Exception {
		String url =getAccessTokenByCodeUrl(code);
		log.debug(url);
		String json=RequestTaskService.sendDataStream(url, null);
		log.debug(json);
		try {
			GetAccessTokenMessage respMessage=GsonUtils.fromGson(json, GetAccessTokenMessage.class);
			return respMessage;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(json);
			return null;
		}
	}
	private static String getAccessTokenByCodeUrl(String code) {
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +WXKeys.WX_EMO_APPID+
				"&secret=" +WXKeys.WX_EMO_SECRET+
				"&code=" +code+
				"&grant_type=authorization_code";
		return url;
	}
	public static String getCodeByAuthorizeUrl(String redirectUrl,boolean isGetUserInfo,String wechat_redirect,String state) {
		String scope=isGetUserInfo? "snsapi_userinfo"	: "snsapi_base" ;
		String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WXKeys.WX_EMO_APPID+
				"&redirect_uri="+redirectUrl+
				"&response_type=code" +
				"&scope=" +scope+
				"&state=" +state+"#wechat_redirect";
				if(!StringUtils.isNullOrEmpty(wechat_redirect))
					url+="="+wechat_redirect;
		return url;
	}
	
}
